package cn.edu.nuc.android.oweibo.tasks;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import weibo4android.Weibo;
import weibo4android.http.ImageItem;
import android.content.ContentResolver;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;

public class PostPhotoAsyncTask extends AsyncTask<Object, Void, weibo4android.Status> {

	private PostPhotoResponder responder;
	private Weibo weibo;
	private Context context;
	
	public PostPhotoAsyncTask(PostPhotoResponder responder, Weibo weibo, Context context) {
		super();
		this.responder = responder;
		this.weibo = weibo;
		this.context = context;
	}

	public interface PostPhotoResponder {
		public void photoPosting();
		public void photoPosted(weibo4android.Status status);
	}

	@Override
	protected weibo4android.Status doInBackground(Object... params) {
		String content = (String)params[0]; // 要发送的微博文本内容
		Uri photoUri = (Uri)params[1]; // 要发送的微博图片Uri地址
		weibo4android.Status status = null; // 用于返回
		ImageItem imageItem; // 用于保存图片内容
		InputStream in;
		byte[] bytes;
		ContentResolver resolver = context.getContentResolver();
		
		try {
			in = resolver.openInputStream(photoUri);
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			byte[] temp = new byte[4096];
			int l;
			while (-1 != (l = in.read(temp))) {
				bout.write(temp, 0, l);
			}
			bout.flush();
			bytes = bout.toByteArray();
			imageItem = new ImageItem(bytes);
			status = weibo.uploadStatus(content, imageItem);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return status;
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		responder.photoPosting();
	}

	@Override
	protected void onPostExecute(weibo4android.Status result) {
		super.onPostExecute(result);
		responder.photoPosted(result);
	}

}
